package com.highveldsky.appengine.xmppplay;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class SendMessage extends HttpServlet {

	private static final Logger log = Logger.getLogger(SendMessage.class.getName());
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		log.info("Sending XMPP message");
		
		JID jid = new JID(req.getParameter("recipient"));
		String msgBody = req.getParameter("message");
		Message msg = new MessageBuilder()
		.withRecipientJids(jid)
		.withBody(msgBody)
		.build();

		boolean messageSent = false;
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		SendResponse status = xmpp.sendMessage(msg);
		messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);

		resp.setContentType("text/plain");
		resp.getWriter().println("Message sending status: "+messageSent);
		
	}

}
